package cn.gyx.hrm.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static cn.gyx.hrm.constants.RabbitMQConstants.*;


@Configuration
public class RabbitMQConfig {


    //1.定义交换机
    @Bean
    public Exchange exchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME_TOPIC).durable(true).build();
    }
    // 2.短信队列
    @Bean
    public Queue smsQueue(){
        return new Queue(QUEUE_NAME_SMS,true);
    }
    // 3.消息站队列
    @Bean
    public Queue systemMessageQueue(){
        return new Queue(QUEUE_NAME_SYSTEM_MESSAGE,true);
    }
    // 4.邮件队列
    @Bean
    public Queue emailQueue(){
        return new Queue(QUEUE_NAME_EMAIL,true);
    }

    // 绑定队列
    // 绑定短信
    @Bean
    public Binding smsQueueBinding() {
        return BindingBuilder.bind(smsQueue()).to(exchange()).with("#.sms").noargs();
    }
    // 绑定消息站
    @Bean
    public Binding systemMessageQueueBinging() {
        return BindingBuilder.bind(systemMessageQueue()).to(exchange()).with("#.message").noargs();
    }
    // 绑定邮件
    @Bean
    public Binding emailQueueBinding() {
        return BindingBuilder.bind(emailQueue()).to(exchange()).with("#.email").noargs();
    }
    //定义RabbitTemplate 指定 JSON转换器
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //1.把要发送的消息内容 ，交换机，rontkey等都保存下来到Mysql
        //2.后续可以用来重写发送消息，甚至可以使用一个定时任务不停的重试，可以甚至一个最大重试次数
        //设置消息回调
        rabbitTemplate.setMandatory(true);

        return rabbitTemplate;
    }
}